//
//  CZSearchView.swift
//  weibo
//
//  Created by Apple on 16/3/8.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

class CZDiscoverSearchView: UIView {

    // MARK:    连线控件
    @IBOutlet weak var btnSearch: UIButton!
    
    @IBOutlet weak var searchTextField: UITextField!
    
    //  文本框距离右边的约束
    @IBOutlet weak var searchTextFieldRightCons: NSLayoutConstraint!
    
    //  类方法创建视图
    class func discoverSearchView() -> CZDiscoverSearchView {
        return UINib(nibName: "CZDiscoverSearchView", bundle: nil).instantiateWithOwner(nil, options: nil).last! as! CZDiscoverSearchView
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    //  使用这个必须要调用        super.init(coder: aDecoder)，要不然使用nib加载xib会报错
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = UIColor.clearColor()
        //  设置当前视图的宽度
        frame.size.width = UIScreen.mainScreen().bounds.width
        //  设置左侧视图的图片及frame
        let imageView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        imageView.frame =  CGRectMake(0, 0, frame.height, frame.height)

        //  设置搜索框左侧的图片
        searchTextField.leftView = imageView
        //  左侧按钮总是显示出来
        searchTextField.leftViewMode = .Always
        //  设置图片的显示模式,原始大小居中显示
        imageView.contentMode = .Center
        
        
        
    }
    
    //  点击搜索按钮的事件
    @IBAction func btnSearchClick(sender: AnyObject) {
        //  取消第一响应者
        searchTextField.resignFirstResponder()
        //  设置距离右边的间距
        searchTextFieldRightCons.constant = 0
        //  执行动画
        UIView.animateWithDuration(0.25) { () -> Void in
            self.searchTextField.layoutIfNeeded()
        }
    
    }

}

//  UITextField代理方法
extension CZDiscoverSearchView: UITextFieldDelegate {
    func textFieldDidBeginEditing(textField: UITextField) {
        
        //  设置右边的间距等于搜索按钮的宽度
        searchTextFieldRightCons.constant = btnSearch.frame.width
    
        //  约束动画要调用layoutIfNeeded
        UIView.animateWithDuration(0.25) { () -> Void in
            self.searchTextField.layoutIfNeeded()
        }
        
        
    }
}


